package com.gvfish.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.gvfish.entity.Role;
import com.gvfish.entity.User;

@Repository
public class UserDao extends CommonDao<User, Long> {
	private PersistenceManagerFactory persistenceManagerFactory;

	public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
		this.persistenceManagerFactory = pmf;
	}
	@Override
	public PersistenceManager getPersistenceManager() {
		return persistenceManagerFactory.getPersistenceManager();
	}
	public User findById(Long id) {
		return getById( id);
	}
	
	public User findByName(String name){
		String theName = "'"+name+"'";
		List<User> users=getByProperty("name", theName);
		User user = null;
		if(users!=null&&users.size()>0){
			user=users.get(0);
		}
		return user;
	}

	public boolean hasUser(String email) {
		return getByProperty( "email", email).size() != 0;
	}
	

	@Override
	public Class<User> getTClass() {
		return User.class;
	}
	public void changeUserRole(Long roleId,String userName){
		PersistenceManager pm = getPersistenceManager();
		Key roleKey = KeyFactory.createKey(Role.class.getSimpleName(), roleId);
		try{
			User user = pm.getObjectById(User.class, findByName(userName).getId());
			Set<Key> roleKeys = user.getRoleKeys();
			if(roleKeys==null){
				roleKeys = new HashSet<Key>();
				user.setRoleKeys(roleKeys);
			}
			if(roleKeys.contains(roleKey)){
				roleKeys.remove(roleKey);
			}else{
				roleKeys.add(roleKey);
			}
			
		}finally{
			pm.close();
		}
	}
	public void deleteAlltmp(){
		PersistenceManager pm = getPersistenceManager();
		Query query = pm.newQuery(User.class);
//		pm.setDetachAllOnCommit(true);
		List<User> result;
		try {
			result = (List<User>) query.execute();
			for(User user:result){
				pm.deletePersistent(user);
			}
		} finally {
			query.closeAll();
		}
	}

}
